package com.fake_Interviews.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fake_Interviews.Mapper.FeedbackMapper;
import com.fake_Interviews.Mapper.InterviewsMapper;
import com.fake_Interviews.Mapper.LoginMapper;
import com.fake_Interviews.Mapper.PdfMapper;
import com.fake_Interviews.module.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fake_Interviews.controller.InterviewerFeedback_Controller.RECORD_DIR;


@RestController
@RequestMapping("/api/AdminInterface")
public class Admin_Controller {
//    public static final String RECORD_DIR = "./record/";

    @Autowired
    LoginMapper loginMapper;
    LoginExample loginExample;
    LoginExample.Criteria criteria;

    @Autowired
    InterviewsMapper interviewsMapper;
    InterviewsExample interviewsExample;
    InterviewsExample.Criteria interviewsMapperCriteria;
    @Autowired
    FeedbackMapper feedbackMapper;
    FeedbackExample feedbackExample;
    FeedbackExample.Criteria feedbackExampleCriteria;
    @Autowired
    PdfMapper pdfMapper;

    //    获取所有用户的名字
    @GetMapping("getUser")
    public ResponseEntity<List<String>> getUser() {
        loginExample = new LoginExample();
        criteria = loginExample.createCriteria();
        criteria.andUsernameNotEqualTo("admin");
        List<Login> loginList = loginMapper.selectByExample(loginExample);
        List<String> userList = new ArrayList<>();
        for (Login login : loginList) {
            userList.add(login.getUsername());
        }
        return ResponseEntity.ok().body(userList);
    }

    //    添加用户
    @PostMapping("addUser")
    public ResponseEntity<Login> addUser(@RequestBody Login login) {
        if (!login.getUsername().isEmpty() && !login.getPassword().isEmpty()) {
            loginMapper.adduser(login);
        }
//        Login login1 = new Login();
//        login1.setUsername(login.getUsername());
//        login1.setPassword(login.getPassword());
//        login1.setRole("0");
//        loginMapper.insert(login1);
        loginExample = new LoginExample();
        int Size = loginMapper.selectByExample(loginExample).size();
        return ResponseEntity.ok().body(loginMapper.selectByPrimaryKey(Size));
    }

    //    插入面试者信息
    @PostMapping("postTask")
    public ResponseEntity<String> postTask(@RequestBody Map<String, Object> taskMap) throws ParseException {
        Base64.Decoder decoder = Base64.getDecoder();

        String interviewee = (String) taskMap.get("interviewee");
        String interviewer = (String) taskMap.get("interviewer");
        String timeStr = (String) taskMap.get("time");
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStr);
        String interviewCont = (String) taskMap.get("base64");

        Interviews interviews = new Interviews();

        loginExample = new LoginExample();
        criteria = loginExample.createCriteria();
        criteria.andUsernameEqualTo(interviewer);
        int interviewerId = loginMapper.selectByExample(loginExample).get(0).getId();
        interviews.setInterviewer(interviewerId);

        loginExample = new LoginExample();
        criteria = loginExample.createCriteria();
        criteria.andUsernameEqualTo(interviewee);
        int intervieweeId = loginMapper.selectByExample(loginExample).get(0).getId();
        interviews.setJobseekers(intervieweeId);
        interviews.setInterviewtime(date);
        interviews.setStatus(null);
        interviewsMapper.insert(interviews);
        List<Interviews> interviewsList = interviewsMapper.selectByExample(interviewsExample);

        Feedback feedback_new = new Feedback();
        feedback_new.setId(interviewsList.get(interviewsList.size() - 1).getId());
        feedback_new.setInterviewsId(interviewsList.get(interviewsList.size() - 1).getId());
        feedbackMapper.insert(feedback_new);

        if (!interviewCont.isEmpty()) {
            Pdf pdf = new Pdf();
            pdf.setInterviewsId(interviewsList.get(interviewsList.size() - 1).getId());
            pdf.setPdf(decoder.decode(interviewCont));
            pdfMapper.insert(pdf);
        }
        return ResponseEntity.ok().body("200");
    }

    //获取文件
    @PostMapping("postDocument/{id}")
    public ResponseEntity<String> postDocument(@RequestBody MultipartFile myFile, @PathVariable Integer id) {
        System.out.println(id);
//        System.out.println(myFile);
//        byte[] a = myFile.getBytes();
        return null;
    }

    //获取所有的面试信息
    @GetMapping("getInformation")
    public ResponseEntity<List<Map<String, Object>>> getInformation() {
        interviewsExample = new InterviewsExample();
        List<Interviews> interviewsList = interviewsMapper.selectByExample(interviewsExample);
        return ResponseEntity.ok().body(InterviewInformation(interviewsList));
    }
    public List<Map<String, Object>> InterviewInformation(List<Interviews> interviewsList){
        List<Map<String, Object>> mapList = new ArrayList<>();

        for (int i = 0; i < interviewsList.size(); i++) {
            Map<String, Object> objectMap = new HashMap<>();

            Login interviewer = loginMapper.selectByPrimaryKey(interviewsList.get(i).getInterviewer());
            objectMap.put("Interviewer", interviewer.getUsername());//面试管官
            objectMap.put("JobSeekers", loginMapper.selectByPrimaryKey(interviewsList.get(i).getJobseekers()).getUsername());//求职者
            Feedback feedback = feedbackMapper.selectByPrimaryKey(interviewsList.get(i).getId());
            if (feedback != null) {
                if (feedback.getInterviewtubefeedback() != null) {
                    objectMap.put("Interviewer_Feedback", feedback.getInterviewtubefeedback()); //Interviewer_Feedback 面试管反馈
                } else {
                    objectMap.put("Interviewer_Feedback", "《 空 》");
                }
                if (feedback.getFeedbackfromjobseekers() != null) {
                    objectMap.put("JobSeekers_Feedback", feedback.getFeedbackfromjobseekers()); //Interviewer_Feedback 求职者反馈
                } else {
                    objectMap.put("JobSeekers_Feedback", "《 空 》");
                }
            } else {
                objectMap.put("Interviewer_Feedback", "《 空 》");
                objectMap.put("JobSeekers_Feedback", "《 空 》");

            }

            objectMap.put("InterviewTime", interviewsList.get(i).getInterviewtime());
            objectMap.put("id", interviewsList.get(i).getId());
            if (interviewsList.get(i).getStatus() == null) {
                objectMap.put("Status", "null");
            } else if (interviewsList.get(i).getStatus()) {
                objectMap.put("Status", "true");
            } else {
                objectMap.put("Status", "false");
            }
            mapList.add(objectMap);
        }

        return mapList;
    }

    //    删除选择的面试场
    @PostMapping("del")
    public ResponseEntity<List<Interviews>> del(@RequestBody Map<String, Object> map) {
        List<Integer> idList = (List<Integer>) map.get("id");
        for (int i = 0; i < idList.size(); i++) {
            feedbackExample = new FeedbackExample();
            feedbackExampleCriteria = feedbackExample.createCriteria();
            feedbackExampleCriteria.andInterviewsIdEqualTo(idList.get(i));
            List<Feedback> feedback = feedbackMapper.selectByExample(feedbackExample);
            if (feedback.size() > 0) {
                feedbackMapper.deleteByPrimaryKey(feedback.get(0).getId());
            }
            interviewsMapper.deleteByPrimaryKey(idList.get(i));
        }
        interviewsExample = new InterviewsExample();
        List<Interviews> interviewsList = interviewsMapper.selectByExample(interviewsExample);
        return ResponseEntity.ok().body(interviewsList);
    }

    //    按照时间排序
    @GetMapping("TimeSortBy")
    public ResponseEntity<List<Map<String, Object>>> TimeSortBy() {
        List<Interviews> interviewsList = interviewsMapper.TimeSortBy();
        return ResponseEntity.ok().body(InterviewInformation(interviewsList));
    }


    //    获取录音
    @GetMapping("DownloadRecording/{id}")
    public ResponseEntity<Map<String, Object>> DownloadRecording(@PathVariable Integer id) throws IOException {
        System.out.println(id);
        String path = RECORD_DIR + id + ".wav";
        ArrayList<Integer> arrayList = new ArrayList<>();
        Map<String, Object> objectMap = new HashMap<>();

        File file = new File(path);
        if (!file.exists()) {
            objectMap.put("key", "");
        } else {
            InputStream in = new BufferedInputStream(new FileInputStream(path));
            //当文件没有结束时，每次读取一个字节显示
            byte[] data;
            data = in.readAllBytes();
            in.close();
            objectMap.put("key", data);
        }

        return ResponseEntity.ok().body(objectMap);
    }
}